package com.taoye.thread;

import cn.hutool.core.date.DateUtil;

public class Demo33 {
	public static void main(String[] args) throws InterruptedException {
		Demo33Service service = new Demo33Service();
		Thread t = new Demo33ThreadA(service);
		t.setName("A");
		t.start();
		Thread.sleep(500);
		Thread t1 = new Demo33ThreadB(service);
		t1.setName("B");
		t1.start();
	}
}

class Demo33Service {
	private String lock = "LOCK-A";

	/**
	 * 这里使用字符串作为参数，用于使用锁
	 */
	public void fun() {
		synchronized (lock) {
			try {
				System.out.println(Thread.currentThread().getName() + "线程执行了fun1，当前时间：" + DateUtil.now());
				//在这里A线程进来的时候，修改了锁定对象的值
				if(Thread.currentThread().getName().equals("A")) {
					lock = "LOCK-B";
				}
				Thread.sleep(2000);
				System.out.println(Thread.currentThread().getName() + "线程fun1执行结束，当前时间：" + DateUtil.now());
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

class Demo33ThreadA extends Thread {
	Demo33Service service;

	public Demo33ThreadA(Demo33Service service) {
		this.service = service;
	}

	@Override
	public void run() {
		// 这里调用的不是静态方法
		service.fun();
	}
}

class Demo33ThreadB extends Thread {
	
	Demo33Service service;

	public Demo33ThreadB(Demo33Service service) {
		this.service = service;
	}

	@Override
	public void run() {
		service.fun();
	}
}
